package net.pinnoocle.playcommon.utils;

import cn.hutool.core.date.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ye
 * @Description
 * @create 2021-10-22 10:19
 */
@Slf4j
public class HelpUtils {

    /**
     * 获取24位字符的UUID
     * @return
     */
    public static String get24UUID(){
        UUID id= UUID.randomUUID();
        String[] idd = id.toString().split("-");
        return idd[0]+idd[1]+idd[4];
    }

    /**
     * 获取UUID
     * @return
     */
    public static String getUUID(){
        String uuid = UUID.randomUUID().toString();
        //去掉“-”符号
        return uuid.replaceAll("-", "");
    }

    /**
     * 数字保留2位小数
     * @param num
     * @return
     */
    public static double setScaleNumber(Double num){
        BigDecimal bg = new BigDecimal(num);
        return bg.setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    /**
     * 获取百分百
     * @param leftNum
     * @param rightNum
     * @return
     */
    public static String getPercent(Integer leftNum,Integer rightNum){
        if(rightNum == 0){
            return "0%";
        }
        double scale = HelpUtils.setScaleNumber((double) leftNum / rightNum);
        return BigDecimalMathUtil.mul(scale,100)+"%";
    }

    /**
     * 获取百分百
     * @param leftNum
     * @param rightNum
     * @return
     */
    public static String getPercent(Double leftNum,Double rightNum){
        if(rightNum == 0){
            return "0%";
        }
        double scale = HelpUtils.setScaleNumber((double) leftNum / rightNum);
        return BigDecimalMathUtil.mul(scale,100)+"%";
    }

    /**
     * 获取比例（没有百分号）
     * @param leftNum
     * @param rightNum
     * @return
     */
    public static double getPercentNoCent(Integer leftNum,Integer rightNum){
        if(rightNum == 0){
            return 0;
        }
        return HelpUtils.setScaleNumber((double) leftNum / rightNum);
    }

    /**
     * 获取客单价
     * @param turnover
     * @param number
     * @return
     */
    public static double getPreTransaction(Double turnover,Integer number){
        if(number == 0){
            return 0.00;
        }
        return HelpUtils.setScaleNumber((double) turnover / number);
    }


    /**
     * 时间戳转日期
     * @param time
     * @return
     */
    public static Date getDateByTime(String time){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date(Long.parseLong(time) * 1000));
        return DateUtil.parse(format,"yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 根据时间类型获取开始结束时间
     * @param typTime 0 近一个月 1 本周 2 当天
     * @return
     */
    public static HashMap<String,String> getStartAndEndDate(Integer typTime){
        String today = DateUtil.today();
        String startDate = "";
        String endDate = "";
        if(typTime == 2){
            startDate = today + " 00:00";
            endDate = today + " 23:59";
        }else if(typTime == 1){
            endDate = DateUtil.formatDate(new Date());
            startDate = DateUtil.formatDate(DateUtil.offsetDay(DateUtil.parse(today), -7));
        }else if(typTime == 0){
            endDate = DateUtil.formatDate(new Date());
            startDate = DateUtil.formatDate(DateUtil.offsetDay(DateUtil.parse(today), -30));
        }
        HashMap<String, String> stringHashMap = new HashMap<>();
        stringHashMap.put("startDate",startDate + " 23:59");
        stringHashMap.put("endDate",endDate+ " 00:00");
        return stringHashMap;
    }



    /**
     * 随机获取9位数字
     * @return
     */
    public static String getRandomNumber() {
        String basePrefix = "123456789";
        String baseSuffix = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        int prefixPosition = random.nextInt(basePrefix.length());
        sb.append(basePrefix.charAt(prefixPosition));
        for (int i = 0; i < 8; i++) {
            int number = random.nextInt(baseSuffix.length());
            sb.append(baseSuffix.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 生成纯数字的订单号
     * @return
     */
    public static String getOrderNumber(){
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateLong = formatter.format(currentTime);
        int x = (int)(Math.random()*900)+100;
        return dateLong + x;
    }

    /**
     * 获取结束时间
     * @param startTime
     * @param minutes
     * @return
     */
    public static Date afterTime(Date startTime,int minutes){
        Date newDate = DateUtil.offset(startTime, DateField.MINUTE, minutes);
        return newDate;
    }

    /**
     * 根据秒获取结束时间
     * @param second
     * @return
     */
    public static Date afterTimeBySecond(int second){
        //提前10分钟过期
        int minutes = (second/60-10);
        return DateUtil.offset(new Date(), DateField.MINUTE, minutes);
    }

    /**
     * 字符串日期转time
     * @param dataStr
     * @return
     */
    public static Time getTimeByDate(String dataStr) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("HH::mm");
        Date parse = formatter.parse(dataStr);
        return (Time) parse;
    }

    public static JSONObject parseXml() throws Exception {
        String xml = "<xml><AppId><![CDATA[wxb96de2e1e62c5df6]]></AppId>\n" +
                "<CreateTime>1637138815</CreateTime>\n" +
                "<InfoType><![CDATA[notify_third_fasteregister]]></InfoType><status>0</status>\n" +
                "<msg><![CDATA[OK]]></msg>\n" +
                "<appid><![CDATA[wxc8756a28ac3c034a]]></appid>\n" +
                "<auth_code><![CDATA[queryauthcode@@@02QLITQ38DrNfmIUTdA-S23xKgL838qmFn0P8Bv7t23_HMSIvqkuYJ24qMkI3wW3YYvP7hELzpKOTgE-3GvYng]]></auth_code>\n" +
                "<info>\n" +
                "<name><![CDATA[合肥皮诺客网络科技有限公司]]></name>\n" +
                "<code><![CDATA[91340100096732504M]]></code>\n" +
                "<code_type>1</code_type>\n" +
                "<legal_persona_wechat><![CDATA[pinoocle]]></legal_persona_wechat>\n" +
                "<legal_persona_name><![CDATA[顾有良]]></legal_persona_name>\n" +
                "<component_phone><![CDATA[15705698545]]></component_phone>\n" +
                "</info>\n" +
                "</xml>";
        Map<String, Object> stringStringMap = ParseXmlUtil.xml2map(xml);
        log.info("decryptMsg-resultMap===={}",stringStringMap);
        Object info = stringStringMap.getOrDefault("xml",null);
        JSONObject firstJson = JSON.parseObject(JSONObject.toJSONString(info));
        JSONObject companyInfo = JSON.parseObject(firstJson.getString("info"));
        log.info("firstJson==={}",firstJson);
        log.info("companyInfo==={}",companyInfo);
        return null;
    }

    /**
     * 通过生日获取年龄
     * @param birthdayStr
     * @return
     */
    public static int getAgeByBirth(String birthdayStr) {
        Date birthday = DateUtil.parse(birthdayStr, "yyyy-MM-dd");
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 比较指定时间与当前时间的比较结果
     */
    public static boolean compareDateToNow(Date targetDate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String nowDate = simpleDateFormat.format(new Date());
        String targetDateStr = simpleDateFormat.format(targetDate);
        if (targetDateStr.compareTo(nowDate) <= 0) {
            return true;// 当天或当天之前
        }
        return false;// 当天之后
    }

    /**
     * 判断是不是昨天
     * @param loginDate
     * @return
     */
    public static boolean isYesterday(Date loginDate){
        if(Objects.isNull(loginDate)){
            return true;
        }
        String today = DateUtil.today()+" 00:00:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String loginTime = simpleDateFormat.format(loginDate);
        if (loginTime.compareTo(today) <= 0) {
            return true;// 当天或当天之前
        }
        return false;// 当天之后
    }

    /**
     * 格式化输出易读时间
     * @param targetDate
     * @return
     */
    public static String easyReadTime(Date targetDate){
        Date nowDate = new Date();
        long between = DateUtil.between(targetDate, nowDate, DateUnit.MINUTE);
        if(between <= 1440){
            if(0 < between && between <= 60){
                return between+"分钟前";
            }else if(60 < between){
                return (between/60)+"小时前";
            }
        }
        return DateUtil.format(targetDate,"yyyy-MM-dd");
    }

    /**
     * 获取某天的开始结束时间
     * @param dayStr
     * @return
     */
    public static HashMap<String,String> getDayStartAndEndTime(String dayStr){
        HashMap<String, String> stringHashMap = new HashMap<>();
        if(StringUtils.isBlank(dayStr)){
            String date = DateUtil.today()+"";
            stringHashMap.put("startDate",date + " 00:00");
            stringHashMap.put("endDate",date+ " 23:59");
        }else{
            int year = DateUtil.year(new Date());
            String newStr = dayStr.replace(".", "-");
            String date = year + "-"+ newStr;
            stringHashMap.put("startDate",date + " 00:00");
            stringHashMap.put("endDate",date+ " 23:59");
        }
        return stringHashMap;
    }

    /**
     * 根据年月获取开始结束时间
     * @param yearMonth
     * @return
     */
    public static HashMap<String,String> getMonthStartAndEndTime(String yearMonth){
        HashMap<String, String> stringHashMap = new HashMap<>();
        DateTime parse = null;
        if(StringUtils.isBlank(yearMonth)){
            parse = new DateTime();
        }else{
            parse = DateUtil.parse(yearMonth, "yyyy-MM");
        }
        DateTime startTime = DateUtil.beginOfMonth(parse);
        DateTime endTime = DateUtil.endOfMonth(parse);
        stringHashMap.put("startDate",startTime+"");
        stringHashMap.put("endDate",endTime+"");
        return stringHashMap;
    }

    /**
     * 获取整数趋势值
     * @param todayNum
     * @param yesterdayNum
     * @return
     */
    public static HashMap<String,Object> getNumberTrendValue(Integer todayNum,Integer yesterdayNum){
        HashMap<String, Object> returnMap = new HashMap<>();
        Integer diffValue = todayNum - yesterdayNum;
        if(diffValue == 0){
            returnMap.put("trendType",0);
            returnMap.put("trendValue","0%");
        }else {
            String percent = getPercent(Math.abs(diffValue), yesterdayNum);
            returnMap.put("trendType",diffValue > 0 ? 1 : 2);
            returnMap.put("trendValue",percent);
        }
        return returnMap;
    }

    /**
     * 获取上升值
     * @param todayValue
     * @param yesterdayValue
     * @return
     */
    public static HashMap<String, Object> getNumberTrendValue(double todayValue, double yesterdayValue) {
        HashMap<String, Object> returnMap = new HashMap<>();
        Double diffValue = todayValue - yesterdayValue;
        if(diffValue == 0){
            returnMap.put("trendType",0);
            returnMap.put("trendValue","0%");
        }else {
            String percent = getPercent(Math.abs(diffValue), yesterdayValue);
            returnMap.put("trendType",diffValue > 0 ? 1 : 2);
            returnMap.put("trendValue",percent);
        }
        return returnMap;
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    public static String getRandomStr(int length) {
        String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }


    public static void main(String[] args) throws Exception {

        Long a = 1639186482857L;
        //System.out.println(s);

    }
}
